/**
 * Created by evil on 17-2-23.
 */

var active_typeId;

$(function ()
{
    meal.init();
    meal.tabs();
    meal.type_list();
    meal.add_meal();
    meal.submit_meal();
});

var meal = {
    init: function ()
    {
        $('#setting-css').attr('href', '/static/css/setting_meal.css');
        $('#meal-list').removeClass('hidden');
    },
    tabs: function ()
    {
        var li = $('.nav-tabs').find('li');
        /*初始化列表*/
        var typeId = $(li[0]).find('a').attr('content');
        active_typeId = typeId;
        mealList.getData(typeId);

        li.click(function ()
        {
            if ($(this).find('a').attr('content') != undefined)
            {
                li.removeClass('active');
                $(this).addClass('active');
                typeId = $(this).find('a').attr('content');
                active_typeId = typeId;
                mealList.getData(typeId);
            }
        });
    },
    type_list: function ()
    {
        var dialog = $('#type-list-dialog');
        $('#type-list-btn').click(function ()
        {
            dialog.modal('show');

            loadTypeList()
        });

        $('#add-type').click(function ()
        {
            meal.type();
        })
    },
    type: function (id, type)
    {
        var dialog = $('#fix-type-dialog');
        dialog.modal('show');
        if (id == null)
            dialog.find('h4').text('增加菜品类型');
        else
        {
            dialog.find('h4').text('修改->ID:' + id);
            dialog.find('input').val(type);
        }

        $('#type-submit').click(function ()
        {
            if (dialog.find('input').val() == '')
                return null;

            $(this).addClass('disabled');

            var url = '/setting/meal/post/type';
            if (id == null)
                url += '/new';
            $.post(url, {
                id: id,
                type: dialog.find('input').val()
            }, function (data)
            {
                if (data == true)
                {
                    toastr.success("提交成功！");
                    dialog.modal('hide');
                    loadTypeList();
                }
                else
                    toastr.error("提交失败！");

                $('#type-submit').removeClass('disabled');
            });
        })
    },
    type_state: function (id, state)
    {
        $.post('/setting/meal/post/type/state', {
            id: id,
            state: !state
        }, function (data)
        {
            if (data == true)
                loadTypeList();
        });
    },
    add_meal: function ()
    {
        $('#add-meal').click(function ()
        {
            $('#meal-dialog').modal('show');
            mealDialog.getData();
        })
    },
    submit_meal: function ()
    {
        $('#meal-submit').click(function ()
        {
            cleanInputHelp();

            var dialog = $('#meal-dialog');

            var name = $('#name');
            var synopsis = $('#synopsis');
            var mealType = $('#mealType');
            var cookType = $('#cookType');
            var price = $('#price');
            var cost = $('#cost');
            var mealMonthStart = $('#mealMonthStart');
            var mealMonthEnd = $('#mealMonthEnd');
            var img = $('#img');

            var sum = 0;

            sum += isInputNull(name);
            sum += isInputNull(mealType);
            sum += isInputNull(cookType);
            sum += isInputNull(price);

            if (sum != 4)
                return null;
            if (mealMonthStart.val() == '' && mealMonthEnd.val() != '')
                return null;
            if (mealMonthEnd.val() == '' && mealMonthStart.val() != '')
                return null;

            $(this).addClass('disabled');

            var url;
            var options;

            if (dialog.find('h4').find('span').length > 0)
            {/*修改*/
                url = '/setting/meal/post/meal';
                /*有图片时，更换地址*/
                if (img.val() != '')
                    url += '_img';

                options = {
                    url: url,
                    type: 'post',
                    success: function (data)
                    {
                        if (JSON.stringify(data).toString() == '\"true\"')
                        {
                            mealList.getData(active_typeId);
                            toastr.success('提交成功，请关闭窗口查看！');
                        }
                        else
                            toastr.error('出现错误，请检查后重试！' + data);

                        $('#meal-submit').removeClass('disabled');
                    },
                    error: function ()
                    {
                        $('#meal-submit').removeClass('disabled');
                    }
                };

                $(".input").ajaxSubmit(options);
            }
            else
            {/*新增*/
                url = '/setting/meal/post/meal/new';
                /*有图片时，更换地址*/
                if (img.val() != '')
                    url += '_img';

                options = {
                    url: url,
                    type: 'post',
                    success: function (data)
                    {
                        if (JSON.stringify(data).toString() == '\"true\"')
                        {
                            mealList.getData(active_typeId);
                            toastr.success('提交成功，请关闭窗口查看！');
                        }
                        else
                            toastr.error('出现错误，请检查后重试！' + data);

                        $('#meal-submit').removeClass('disabled');
                    },
                    error: function ()
                    {
                        $('#meal-submit').removeClass('disabled');
                    }
                };

                $(".input").ajaxSubmit(options);
            }
        });
    }
};

function loadTypeList()
{
    $.get('/setting/meal/get/type/list', function (list)
    {
        var html;
        var body = $('#type-list-dialog').find('tbody');
        body.empty();
        for (var i = 0; i < list.length; i++)
        {
            html = "<tr>";
            html += "<td><a href='javascript:meal.type(" + list[i].mealTypeId + ",\""
                + list[i].type + "\")'>" + +list[i].mealTypeId + "</a></td>";
            html += "<td>" + list[i].type + "</td>";
            if (list[i].state)
                html += "<td><button class='btn btn-xs btn-success' " +
                    "onclick='meal.type_state(" + list[i].mealTypeId + "," + list[i].state + ")'>" +
                    "开启中</button></td>";
            else
                html += "<td><button class='btn btn-xs btn-warning'" +
                    "onclick='meal.type_state(" + list[i].mealTypeId + "," + list[i].state + ")'>" +
                    "关闭中</button></td>";
            html += "</tr>";
            body.append(html);
        }
    });
}

var mealList = new Vue({
    el: '#meal-list',
    data: {
        list: []
    },
    methods: {
        getData: function (typeId)
        {
            $.get('/setting/meal/get/list', {
                typeId: typeId
            }, function (ls)
            {
                mealList.list = ls;
            });
        },
        fix_meal: function (meal)
        {
            $('#meal-dialog').modal('show');
            mealDialog.getData(meal);
        },
        show_time: function (name, add, fix)
        {
            toastr.info("名称：" + name + "\n<br>创建：" + add + "\n<br>修改：" + fix);
        },
        updateMarket: function (mealId, market, event)
        {
            var i;
            var btn = $(event.target);
            if (market)
            {
                btn.find('span').removeClass('glyphicon-eye-open');
                btn.find('span').addClass('glyphicon-eye-close');
            } else
            {
                btn.find('span').removeClass('glyphicon-eye-close');
                btn.find('span').addClass('glyphicon-eye-open');
            }
            $.post('/setting/meal/post/market', {
                mealId: mealId,
                market: !market
            }, function (data)
            {
                if (data == true)
                {
                    toastr.success('ID:' + mealId + ' 更新成功');

                    for (i = 0; i < mealList.list.length; i++)
                        if (mealList.list[i].mealId == mealId)
                        {
                            mealList.list[i].market = !mealList.list[i].market;
                            break;
                        }
                }
                else
                {
                    toastr.error('ID:' + mealId + ' 更新失败，请重试！');
                    if (market)
                    {
                        btn.find('span').removeClass('glyphicon-eye-close');
                        btn.find('span').addClass('glyphicon-eye-open');
                    } else
                    {
                        btn.find('span').removeClass('glyphicon-eye-open');
                        btn.find('span').addClass('glyphicon-eye-close');
                    }
                }
            });
        }
    }
});

var mealDialog = new Vue({
    el: '#meal-dialog',
    data: {
        title: "",
        selectMonthStart: '',
        selectMonthEnd: '',
        selectMealTypeId: '',
        selectCookTypeId: '',
        meal: {},
        mealType: [],
        cookType: [],
        month: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
    },
    methods: {
        getData: function (meal)
        {
            if (meal == null)
            {
                mealDialog.title = '新增菜品';
                /*清空过时数据*/
                mealDialog.selectMonthStart = '';
                mealDialog.selectMonthEnd = '';
                mealDialog.selectMealTypeId = '';
                mealDialog.selectCookTypeId = '';
                mealDialog.meal = {};
                mealDialog.mealType = [];
                mealDialog.cookType = [];
            }
            else
            {
                mealDialog.title = '修改菜品 ID:<span>' + meal.mealId + '</span>';
                mealDialog.meal = meal;

                if (meal.monthToMarket != null)
                {
                    mealDialog.selectMonthStart = meal.monthToMarket.split('-')[0];
                    mealDialog.selectMonthEnd = meal.monthToMarket.split('-')[1];
                }
            }
            //TODO:2017-02-27 19:22:18 此处包含已经关闭的项目，红色显示
            $.get('/setting/meal/get/mealtype/list', function (list)
            {
                if (list == null)
                {
                    toastr.error('发生错误！');
                    return null;
                }

                mealDialog.mealType = list;

                /*由于类型需要异步加载，所以必须等待列表加载完成，才能设定默认值*/
                if (meal != null)
                    mealDialog.selectMealTypeId = meal.mealType.mealTypeId;
            });
            //TODO:2017-02-27 19:22:18 此处包含已经关闭的项目，红色显示
            $.get('/setting/meal/get/cooktype/list', function (list)
            {
                if (list == null)
                {
                    toastr.error('发生错误！');
                    return null;
                }

                mealDialog.cookType = list;

                /*由于类型需要异步加载，所以必须等待列表加载完成，才能设定默认值*/
                if (meal != null)
                    mealDialog.selectCookTypeId = meal.cookType.typeOfWorkId;
            });
        }
    }
});


function isInputNull(it, help)
{
    if (it.val() == null || it.val().toString().trim() == '')
    {
        it.parent().parent().addClass('has-error');
        if (help == null)
            it.parent().find('span').text('输入为空！');
        else
            it.parent().find('span').text(help);

        return 0;
    }
    return 1;
}

function cleanInputHelp()
{
    var input = $('.input');
    input.find('.form-group').removeClass('has-error');
    input.find('.help-block').empty();
}










